window.onload = function() {
    cascadingList(); //下拉级联列表
    uploadPics(); //上传图片
    pickLabels(); //选中标签
    releaseProduction(); //将发布内容保存到本地
}
$(function() {
    //判断是否登录
    var userInfo = sessionStorage['users'];
    if (userInfo == null) {
        alert('请先登录！');
        location.href = 'personalCenter.html';
        $('#userName').html("未登录");
        $('#login').html('登录/注册')
    } else {
        var user = JSON.parse(sessionStorage['users'])
        $('#userName').html(user[0].Name)
        $('#login').html('退出登录')
    }
})
var allGoods = [
    ['台式机', '手表手环', '单反相机', '充电宝', '耳机', '手机', '电脑配件', '路由器', '其他'],
    ['教科书', '文学', '小说', '电子书', '教育考试', '动漫', '其他'],
    ['裤子', '衣服', '帽子', '鞋子', '箱子', '包包', '雨伞', '其他'],
    ['自行车', '旱冰鞋', '平衡车', '滑板', '油车', '电动车', '其他'],
    ['球类', '球拍', '运动鞋', '运动装备', '健身器材', '其他'],
    ['电磁炉', '洗衣机', '冰箱', '风扇', '电饭煲', '电吹风', '音响', '其他'],
    ['化妆护肤', '小工具', '学习用品', '其他'],
    ['游戏周边', '充值卡', '各类账号', '其他'],
    ['书法', '绘画', '工艺品', '服装设计', '其他'],
    ['吉他', '钢琴', '尤克里里', '民族管弦', '西洋管弦', '打击乐器', '乐器配件', '电脑音乐', '口琴/竖笛', '电子琴', '其他'],
    ['其他']
];

//下拉级联列表
function cascadingList() {
    var category = document.querySelector('.category'); //第一级下拉列表
    var goods = document.querySelector('.goods'); //第二级下拉列表
    category.onchange = function() {
        goods.options.length = 0;
        var index = this.selectedIndex;
        // console.log(category.options[index].text);
        var theGoods = allGoods[index];
        var length = theGoods.length;
        for (var i = 0; i < length; i++) {
            var goodsOption = new Option(theGoods[i], theGoods[i]);
            goods.options.add(goodsOption);
        }
    }
}

//上传图片
var product_pictures = [];

function uploadPics() {
    var inputFile = document.querySelector('[type="file"]')
    var upload = document.querySelector('.upload');
    upload.onclick = function() {
        inputFile.click();
    }
    inputFile.onchange = function() {
        var newImg = document.createElement('img');
        newImg.className = 'newImg';
        inputFile.parentNode.insertBefore(newImg, upload);
        var fileReader = new FileReader()
        var reg = /^image/gi
        var flag = reg.test(inputFile.files[0].type);
        // console.log(inputFile.files[0].name);
        product_pictures.push(inputFile.files[0].name);
        if (inputFile.files[0].size < Math.pow(1024, 2) && flag) {
            fileReader.onload = function(e) {
                newImg.src = e.target.result
            }
            fileReader.readAsDataURL(inputFile.files[0])
        } else {
            alert("图片上传失败！")
            newImg.parentNode.removeChild(newImg);
        }
    }
}

//选中标签
var flag = [false, false, false, false, false, false, false];

function pickLabels() {
    var label = document.querySelector('.label');
    var labelBtn = label.querySelector('.labelBtn');
    var labelInput = label.querySelector('.labelInput');
    getColor();
    labelBtn.onclick = function() {
        var spans = label.querySelectorAll('span');
        if (labelInput.value != '') {
            var newSpan = spans[0].cloneNode(true);
            newSpan.innerHTML = labelInput.value;
            label.insertBefore(newSpan, labelInput);
            flag.push(true);
            newSpan.style.backgroundColor = 'rgb(72, 212, 166)';
            newSpan.style.color = '#fff';
            labelInput.value = '';
            getColor();
        } else {
            alert('请在文本框中输入内容后，再点击添加按钮！');
        }

    }

    function getColor() {
        var spans = label.querySelectorAll('span');
        var length = spans.length;
        for (let i = 0; i < length; i++) {
            spans[i].onclick = function() {
                console.log('点击了');
                if (flag[i]) {
                    flag[i] = false;
                    this.style.backgroundColor = '#eee';
                    this.style.color = '#000';
                } else {
                    flag[i] = true;
                    this.style.backgroundColor = 'rgb(72, 212, 166)';
                    this.style.color = '#fff';
                }
            }
        }
    }
}

//将发布内容保存到本地
function releaseProduction() {
    var productName = document.querySelector('.productName').querySelector('input');
    var category = document.querySelector('.category');
    var goods = document.querySelector('.goods');
    var productPrice = document.querySelector('.productPrice').querySelector('input');
    var originalPrice = document.querySelector('.originalPrice').querySelector('input');
    var tel = document.querySelector('.tel').querySelector('input');
    var product_details = document.querySelector('.product_details').querySelector('textarea');
    var postage = document.querySelector('.postage').querySelector('input');

    var submitBtn = document.querySelector('.submit');
    var releaseProductions = [];
    submitBtn.onclick = function() {
        releaseProductions.push({
            "productName": productName.value,
            "category": [category.options[category.selectedIndex].text, goods.options[goods.selectedIndex].text],
            "productPrice": productPrice.value,
            "originalPrice": originalPrice.value,
            "label": getLabelContent(),
            "tel": tel.value,
            "product_details": product_details.value,
            "upload_pics": product_pictures,
            "postage": postage.value
        })
        localStorage['releaseProductions'] = JSON.stringify(releaseProductions);
    }

    function getLabelContent() {
        var label = document.querySelector('.label');
        var arr = [];
        var spans = label.querySelectorAll('span');
        var length = spans.length;
        for (let i = 0; i < length; i++) {
            if (flag[i]) {
                // arr += spans[i].innerHTML;
                arr.push(spans[i].innerHTML);
            }
        }
        return arr;
    }
}

function out() {
    sessionStorage.clear()
    if ($('#login').html() == '退出登录') {
        location.href = 'index.html'
    } else {
        location.href = 'login.html'
    }
}